package com.chensi.admin.shop.service.impl;

import com.chensi.admin.shop.domain.GoodsPic;
import com.chensi.admin.shop.service.GoodsPicService;
import com.chensi.admin.shop.util.SpecificationUtil;
import com.chensi.admin.shop.dao.GoodsPicRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author si.chen
 * @date 2019/7/15 13:57
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GoodsPicServiceImpl implements GoodsPicService {

    private final GoodsPicRepository goodsPicRepository;

    @Autowired
    public GoodsPicServiceImpl(GoodsPicRepository goodsPicRepository) {
        this.goodsPicRepository = goodsPicRepository;
    }

    @Override
    public List<GoodsPic> list(GoodsPic entity) {
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        return goodsPicRepository.findAll(this.getSpecification(entity), sort);
    }

    @SuppressWarnings("Duplicates")
    private Specification<GoodsPic> getSpecification(GoodsPic entity) {
        return (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            SpecificationUtil.baseSpecification(root, cb, list, entity);
            if (entity.getGoods() != null && StringUtils.isNotBlank(entity.getGoods().getId())) {
                Predicate predicate = cb.equal(root.get("goods").get("id"), entity.getGoods().getId().trim());
                list.add(predicate);
            }
            query.where(list.toArray(new Predicate[0]));
            return query.getRestriction();
        };
    }
}
